<template>
  <div>
    <table>
      <thead>
      <th v-for="(column, index) in columns" :key="column.label + index">
        {{ column.label }}
        <em v-if="column.sortable">
          <i @click="descending(column)">降序</i> ||
          <i @click="ascending(column)">升序</i>
        </em>
      </th>
      </thead>
    </table>
  </div>
</template>
<script>
export default {
  name: 'KTableHeader',
  props: {
    columns: Array,
    data: Array,
  },
  methods: {
    compareUp(data, propertyName) {
// 升序排序
      if (typeof data[0][propertyName] != 'number') {
// 属性值为⾮数字
        return function (object1, object2) {
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value1.localeCompare(value2)
        }
      } else {
        return function (object1, object2) {
// 属性值为数字
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value1 - value2
        }
      }
    },
    compareDown(data, propertyName) {
// 降序排序
      if (typeof data[0][propertyName] != 'number') {
// 属性值为⾮数字
        return function (object1, object2) {
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value2.localeCompare(value1)
        }
      } else {
        return function (object1, object2) {
// 属性值为数字
          var value1 = object1[propertyName]
          var value2 = object2[propertyName]
          return value2 - value1
        }
      }
    },
    descending(column) {
      this.data.sort(this.compareDown(this.data, column.prop))
    },
    ascending(column) {
      this.data.sort(this.compareUp(this.data, column.prop))
    },
  },
}
</script>
